package org.hry.netty.channelhandler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;

public class ChannelLifeCycleHandler implements ChannelInboundHandler {
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
//        ctx.channel().
        System.out.println("channel" + ctx.channel().toString() + "已经被注册");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel" + ctx.channel().toString() + " 已经被创建，但是还未被注册");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel" + ctx.channel().toString() + " 处于活动状态，可以收发数据了");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel" + ctx.channel().toString() + "没有连接到远程节点");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("channel" + ctx.channel().toString() + "读取到数据：" + msg);
        ReferenceCountUtil.release(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel" + ctx.channel().toString() + "上一个channel的读取数据完成");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("channel" + ctx.channel().toString() + "ChannelInboundHandler的fireUserEventTriggered方法被调用");
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel" + ctx.channel().toString() + "channel的可写状态发生改变");
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel" + ctx.channel().toString() + "handler 添加到 pipeline中");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("channel" + ctx.channel().toString() + "发生异常");
    }
}
